package moodish.testing;

import static org.junit.Assert.*;

import java.io.IOException;
import java.net.UnknownHostException;

import moodish.comm.ClientSideMessage;
import moodish.comm.ServerSideMessage;
import moodish.dummy.ClientCommDummy;
import moodish.dummy.ServerCommDummy;

import org.junit.Test;

public class CommTest {

	@Test
	public void testGetNextMessage() {
		ServerCommDummy server = new ServerCommDummy();
		server.start();
		
		ClientCommDummy client = new ClientCommDummy();
		try {
			client.connect("127.0.0.1", "David");
		} catch (UnknownHostException e) {
			System.out.println("UnknownHostException");
		} catch (IOException e) {
			System.out.println("IOException");
		}
		client.sendMoodishMessage("lol");
		
		ServerSideMessage msg = server.getNextMessage();
		System.out.println(msg.getClientNickname() + " send " + msg.getType()
				+ " with payload " + msg.getPayload());

		client.disconnect();
		server.disconnectClient("David");
		
		server.shutDownServer();
	}

	@Test
	public void testSendNewFriendship() {
		System.out.println("-----------------------------------");
		ServerCommDummy server = new ServerCommDummy();
		server.start();
		
		ClientCommDummy client = new ClientCommDummy();
		ClientCommDummy client1 = new ClientCommDummy();
		ClientCommDummy client2 = new ClientCommDummy();
		try {
			client.connect("127.0.0.1", "David");
			client1.connect("127.0.0.1", "Joao");
			client2.connect("127.0.0.1", "Joao");
		} catch (UnknownHostException e) {
			System.out.println("UnknowHostException");
		} catch (IOException e) {
			System.out.println("IOException");
		}

		server.sendNewFriendship("David", "Joao");
		server.sendError("Joao", "Error 1");
		if(server.clientIsConnected("Joao")){
			System.out.println("Joao is connected");
			server.sendClientConnected("David", "Joao");
		}
		if(client.isConnected()){
			System.out.println("I'm connected - client");
		}
		
		server.sendMoodishMessage("Joao", "David", "frazzled");
		server.sendMoodishMessage("Joao", "David", "confused");
		server.sendMoodishMessage("Joao", "David", "happy");
		server.sendNewUnfriendship("Joao", "David");
		if(client1.hasNextMessage()){
			System.out.println("Client Joao - I have a new message.");
			ClientSideMessage msg = client1.getNextMessage();
			System.out.println("Mensagem: type " + msg.getType() + " payload " + msg.getPayload() + 
					" sender " + msg.getSendersNickname());
		}
		server.sendNewFriendship("Joao", "David");
		client.friendship("Joao");
		client.unfriendship("Joao");
		
		client.disconnect();
		server.disconnectClient("David");
		
		server.sendClientDisconnected("Joao", "David");
		
		server.shutDownServer();
		
		client1.sendMoodishMessage("ola");
	}
}